<?php

namespace app\api\controller;


use app\admin\model\BuildingRoomModel;
use app\admin\model\CustomerModel;
use app\admin\model\NoticeModel;
use app\admin\model\NoticeTemplateModel;
use app\common\controller\Api;
use app\common\model\Message;
use think\Db;
use think\Exception;


class Notice extends Api
{

    protected $noNeedRight = '*';


    public function index()
    {
        $page_size = $this->request->param('page_size', 10);
        $kw = $this->request->param('kw', '');
        $where = [];
        if (!empty($kw)) {
            $where['title'] = ['like', '%' . $kw . '%'];
        }
        $list = NoticeModel::where('user_id', $this->auth->id)
            ->where($where)
            ->field('id,type,title,content,create_time,status,images')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['type_text','create_time_text']);
                if ($item['images']) {
                    $images = explode(',', $item['images']);
                    foreach ($images as &$image) {
                        $image = cdnurl($image);
                    }
                    unset($image);
                    $item['images'] = $images;
                }
            });

        $this->success('success', $list);
    }

    public function add()
    {
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'type|类型' => 'require|in:1,2,3,4',
            'title|标题' => 'require',
            'content|内容' => 'require',
            //'images|图片' => 'length:0,8',
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }
        $params['user_id'] = $this->auth->id;
        $res = NoticeModel::create($params, true);

        if ($res) {
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }
    }


    public function send()
    {
        $id = $this->request->param('id/d');
        if ($id < 1) {
            $this->error('id错误');
        }
        $notice = NoticeModel::get($id);
        if (empty($notice)) {
            $this->error('数据不存在');
        }
        if (empty($notice['renter_ids']) && empty($notice['build_ids'])) {
            $this->error('没有接收人');
        }
        Db::startTrans();
        try {
            $notice->status = 1;
            $notice->save();

            if (!empty($notice['renter_ids'])) {
                $renter_mobiles = CustomerModel::whereIn('id', $notice['renter_ids'])->column('mobile');
                $user_ids = \app\common\model\User::whereIn('mobile', $renter_mobiles)->column('id');
            } else {
                $user_phone_list = \app\common\model\Contract::whereIn('build_id', $notice['build_ids'])->column('user_phone');
                $user_ids = \app\common\model\User::whereIn('mobile', $user_phone_list)->column('id');
            }

            if (empty($user_ids)) {
                throw new Exception('接收人未注册');
            }

            $message_data = [];
            foreach ($user_ids as $uid) {
                $message_data[] = [
                    'user_id' => $uid,
                    'type' => Message::TYPE_FIVE,
                    'title' => $notice['title'],
                    'content' => $notice['content'],
                    'images' => $notice['images'],
                    'other_id' => $notice['id'],
                ];
            }
            (new Message())->saveAll($message_data);

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('发布公告失败：' . $e->getTraceAsString());
            $this->error($e->getMessage());
        }
        $this->success('发送成功');
    }


    public function template()
    {
        $page_size = $this->request->param('page_size', 10);
        $kw = $this->request->param('kw', '');
        $where = [];
        if (!empty($kw)) {
            $where['title'] = ['like', '%' . $kw . '%'];
        }
        $list = NoticeTemplateModel::where($where)
            ->field('id,type,title,content,create_time,images')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['type_text']);
                if ($item['images']) {
                    $images = explode(',', $item['images']);
                    foreach ($images as &$image) {
                        $image = cdnurl($image);
                    }
                    unset($image);
                    $item['images'] = $images;
                }
            });

        $this->success('success', $list);
    }


    public function info()
    {
        $id = $this->request->param('id/d');
        $notice = NoticeModel::get($id);
        if ($notice) {
            $notice = $notice->toArray();
            $notice['images'] = get_all_img_path($notice['images']);
        }

        $this->success('', $notice);
    }

}
